<style> 
#dev_list_panle_div{ position:absolute; left:0px; top:0px; background:#FFFFFF; width:300px;height:100% }
#top_panel { position:absolute; left:10px; top:10px;background-color:rgba(320,138,138,0); width:100%;}
#total_board { position:absolute; right:10px; top:10px; background:#FFFFFF; width:200px;height: 180px;padding:2px;background-color: #F2F2F2;}
</style>
<div id="map_box" style="width: 100%;height: 100%"></div>
<div id="top_panel">
  <form  class="layui-form layui-form-pane " action=""style="padding: 10px;">
    <!-- 地图切换 -->
    <div class="layui-input-inline">
      <select type="text" id="select_map" autocomplete="off" class="layui-input" lay-filter="map" style="height: 30px"></select>
    </div>
    <!-- 查找建筑 -->
    <div class="layui-input-inline">
      <input onkeyup="query_func('building',this.value)" list="building_select" type="text" name="building_select"  placeholder="查找建筑"  autocomplete="off" class="layui-input " >
      <datalist id="building_select"></datalist>
    </div>
    <!-- 查找基站 -->
    <div class="layui-input-inline">
      <input onkeyup="query_func('scanner',this.value)" list="scanner_select" type="text" name="scanner_select"  placeholder="查找基站"  autocomplete="off" class="layui-input">
      <datalist id="scanner_select"></datalist>
    </div>
    <!-- <div class="layui-input-inline">
      <input type="checkbox" name="camera" checked="" title="摄像头" lay-filter="overlay_show_sw">
    </div> -->
    <!-- 搜索地址 -->
    <div class="layui-input-inline">
      <input type="text" list="addr_list"  id="search_address" onchange="search_map(this)"  placeholder="搜索地址" autocomplete="off" class="layui-input" >
      <datalist id="addr_list"></datalist>
    </div>
    <div class="layui-form-mid layui-word-aux"></div>
    <!-- 建筑图标显示开关 -->
    <div class="layui-input-inline">
      <label class="layui-form-label" style="width: 60px;background-color:  rgba(255,255,255,0);border: 0;color: green;font-size: 15px;font-weight: bold;">建筑</label>
      <input type="checkbox" name="building"  checked="" title="建筑" lay-filter="overlay_show_sw" lay-skin="switch" lay-text="ON|OFF">
    </div>
    <!-- 基站图标显示开关 -->
    <div class="layui-input-inline">
      <label class="layui-form-label" style="width: 60px;background-color:  rgba(255,255,255,0);border: 0;color: green;font-size: 15px;font-weight: bold;">基站</label>
      <input type="checkbox" name="scanner"  checked="" title="基站" lay-filter="overlay_show_sw" lay-skin="switch" lay-text="ON|OFF">
    </div>
  </form>
</div>
<!-- 报警设置表单开始 -->
<form  class="layui-form layui-form-pane " action="" id="set_param_form" lay-filter="set_param_form" style="padding: 10px;display: none;">
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">设备ID</label>
      <div class="layui-input-block">
        <input type="text" readonly="" name="device_id"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>
  
  <div class="layui-form-item" >
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">停留报警</label>
      <div class="layui-input-inline">
        <input type="text" name="stop_rate"  placeholder="分钟"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">震动报警</label>
      <div class="layui-input-block">
        <input type="checkbox" name="quake_alarm" lay-skin="switch" lay-filter="switchTest" lay-text="ON|OFF">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <button class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="set_param_submit" id="set_param_submit">提交</button>
  </div>
</form>
<!-- 定制地图人员情况看板 -->
<div id="total_board" style="background-color: #009688;border-radius: 20px">
  <div class="layui-card" style="height: 100%;background-color: #009688;border-radius: 20px;color: white">
    <i style="position: relative;margin: 0 0 0 90%" class="layui-icon layui-icon-close" onclick="total_board_sw('hide')"></i>
    <div class="layui-card-header"><h2 style="color: white">实时统计</h2></div>
    <div class="layui-card-body">
      <h2 id="total_num">总数:0</h2>
      <h2 id="in_room_num">室内:0</h2>
      <h2 id="out_room_num">室外:0</h2>
      <h2 id="danger_num">危险区域:0</h2>
    </div>
  </div>
</div>
<!-- 总看板展示按钮 -->
<button id="total_board_show" class="layui-btn" onclick="total_board_sw('show')" style="position: absolute;right:10px;top: 10px;display: none;"><i class="layui-icon">&#xe62d;</i></button>
<!-- 设备栏展示按钮 -->
<button id="show_sw" class="layui-btn" onclick="dev_panle_sw('show')" style="position: absolute;left:-20px;top: 40%;height: 150px;width: 10px;display: none;"><i class="layui-icon">&#xe66b;</i></button>


<!-- <script type="text/javascript" src="/static/fmap_SDK_v2.7.0_Standalone/fengmap.min.js"></script> -->
<script id="map_js" type="text/javascript" src="/static/js/png_map.js"></script>
<!-- <script src="/static/svg-pan-zoom-master/svg-pan-zoom.js"></script> -->
<!-- <script type="text/javascript" src="/static/amrPlayer-jsdemo/BenzAMRRecorder.js"></script> -->
<!-- <link href="/static/video-js-5.20.1/video-js.css" rel="stylesheet">
<script src="/static/video-js-5.20.1/video.js"></script> -->
<!-- <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.8.1/video-js.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.8.1/video.min.js"></script> -->
<script type="text/javascript">

//异步加载js
// var map_js=document.createElement("script")
// map_js.type="text/javascript"
// map_js.src="/static/js/png_map.js"
// map_js.id='map_js'
// $('.layui-body').append(map_js)

var side_bar='<div class="layui-coutainer" id="dynamic_side_bar">'+
              '<div  style="overflow: auto;height: 165px;">'+
                '<table id="id_tree" class="layui-table"></table>'+
              '</div>'+
              '<div class="layui-row" style="padding: 0px;background-color:#009688;text-align: center;">'+
                '<button id="user_chosed" class="layui-btn layui-btn-xs layui-btn-fluid" onclick="device_status_search(\'all\')">全部</button>'+
              '</div>'+
              '<div class="layui-row" style="padding: 2px;">'+
                '<button id="dev_online" class="layui-btn layui-btn-xs layui-btn-radius" onclick="device_status_search(\'online\')">在线</button>'+
                '<button id="dev_sleep" class="layui-btn layui-btn-normal layui-btn-xs layui-btn-radius" onclick="device_status_search(\'sleep\')">休眠</button>'+
                '<button id="dev_offline" class="layui-btn layui-bg-cyan layui-btn-xs layui-btn-radius" onclick="device_status_search(\'offline\')">离线</button>'+
                '<button id="dev_alarm" class="layui-btn layui-btn-danger layui-btn-xs layui-btn-radius" onclick="device_status_search(\'alarm\')">报警</button>'+
              '</div>'+
             '<form class="layui-form layui-form-pane" action="" style="width:auto;height: 20px;padding: 2px">'+
                  '<div class="layui-form-item">'+
                      '<div class="layui-inline">'+
                          '<div class="layui-input-inline">'+
                              '<input type="text" lay-verify="required" name="search_key" lay-reqtext="请输入搜索内容" placeholder="设备ID/名称" autocomplete="off" class="layui-input" style="width:auto;height: 30px">'+
                          '</div>'+
                          '<div class="layui-inline" >'+
                              '<a type="button" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="dev-search-btn" >搜索</a>'+
                          '</div>'+
                      '</div>'+
                  '</div>'+
              '</form>'+
              '<div class="" id="dev_list_panle">'+
                '<div class="layui-card-body" style="padding: 2px;border: 1px">'+
                  '<table id="dev_list_show" lay-filter="dev_list_show"></table>'+
                '</div>'+
              '</div>'+
            '</div>'
$('.layui-side').empty()
$('.layui-side').append(side_bar)
form.render()
var total_board_sw=function(command){
  if(command=='hide'){
    $('#total_board').hide()
    $('#total_board_show').show()
  }else{
    $('#total_board').show()
    $('#total_board_show').hide()
  } 
}

var body_height=$('.layui-body').height()
var body_width=$('.layui-body').width()
var map_height=body_height-60*body_height/827
var map_width=body_width
// $('#map_box').attr('style','width:'+body_width+'px;height:'+body_height+'px;')

// ----侧边栏模块start---- //

// 渲染树状用户结构，需要增加宽度，增加横向的滚动
var tree_render=function(div_id,user_tree_data,dev_data){
  tree.render({
    elem: '#'+div_id
    ,data: user_tree_data
    ,showCheckbox: false  //是否显示复选框
    ,onlyIconControl:true
    ,id: 'user_tree_id'
    ,isJump: true //是否允许点击节点时弹出新窗口跳转
    ,text: {
            defaultNodeName: '未命名' //节点默认名称
            ,none: '无数据' //数据为空时的提示文本
          }   
    // ,showLine:false
    ,click: function(obj){
      // 选择用户，展示该用户名下的设备
      var check_user = obj.data.name;
      var user_title= obj.data.title
      // 用户状态搜索展示
      user_check['name']=check_user
      user_check['title']=user_title
      var check_user_device=[];
      for(var i=0;i<dev_data.length;i++){
         if(dev_data[i]['owner']===check_user){
          check_user_device.push(dev_data[i])
         }
      }
      if(check_user=='all'){
        device_list_table(dev_data)
      }else{
        device_list_table(check_user_device)
      }
      dev_status_num(check_user,user_title)
    }
  });
}


// 设备列表数据加载函数
var device_list_table=function(table_data){
  // device=table_data
  table.render({
    elem: '#dev_list_show',
    data: table_data,
    id:'device_list',
    skin:'nob',
    size:'sm',
    height: 'full-330',
    cols: [[
        {type: "checkbox", fixed: "left"},
        {field: 'user_name', title: '名称'},
        {field: 'device_id', title: '设备ID',sort:true},
        {field: 'on_off_line', title: '状态',sort:true,templet: function(d){
          var status;
          if(d.on_off_line==='online'){
            status='在'
          }else{
            status='离'
          }
        return status
      }}
    ]],
    // page: true,
    limit:10000000
  });
}

// 按照设备状态展示设备
// 全局变量user_check,用户存储用户树状图上被选中的用户name和title
var user_check={'name':'all','title':'全部'};
var device_status_search=function(dev_status){
  // console.log(dev_status,user_check)
  var user_name=user_check['name']
  var query_status={'online':'on_off_line','sleep':'sleep_status','offline':'on_off_line','alarm':'alarm_status'}
  var dev_status_list=[]
  for(var i=0;i<device.length;i++){
    if(user_name=='all'){
      if(dev_status=='all'){
        dev_status_list.push(device[i])
      }else{
        if(device[i][query_status[dev_status]]==dev_status){
          dev_status_list.push(device[i])
        }
      }
    }else{
      if(dev_status=='all'){
        if(device[i]['owner']==user_name){
          dev_status_list.push(device[i])
        }
      }else{
        if(device[i]['owner']==user_name && device[i][query_status[dev_status]]==dev_status){
          dev_status_list.push(device[i])
        }
      }
    }
  }
  device_list_table(dev_status_list)
}

// 某用户设备状态（在线，离线，报警，休眠）统计函数
var dev_status_num=function(user_name,user_title,dev_data){
  var query_status={'online':'on_off_line','sleep':'sleep_status','offline':'on_off_line','alarm':'alarm_status'}
  var dev_status={}
  for(var k in query_status){
    dev_status[k]=[]
    for(var i=0;i<dev_data.length;i++){
      if(user_name=='all'){
        if(dev_data[i][query_status[k]]==k){
          dev_status[k].push(dev_data[i])
        }
      }else{
        if(dev_data[i]['owner']==user_name && dev_data[i][query_status[k]]==k){
          dev_status[k].push(dev_data[i])
        }
      }
    }
  } ;
  // 把各种状态设备的数量显示到相应的位置
  var status_show_dict={'online':'在线','sleep':'休眠','offline':'离线','alarm':'报警'}
  
  for(var k in dev_status){
    $('#dev_'+k).text(status_show_dict[k]+'('+dev_status[k].length.toString()+')')
  }
  // 某个用户的设备总数量
  var total_num=0;
  if(user_name=='all'){
    total_num=dev_data.length
  }else{
    for(var i=0;i<dev_data.length;i++){
      if(dev_data[i]['owner']==user_name){
        total_num+=1
      }
    }
  }
  $('#user_chosed').text(user_title+'('+total_num.toString()+')')

  return dev_status
}


//把不属于本地图的设备过滤掉
var filter_current_func=function(data,kind){
  var device_filter_list=[]
  console.log(data)
  data.forEach(item=>{
    var location
    // console.log(item,current_map)
    if(kind=='device'){
      location=item.dynamic.location
    }else{
      location=eval('('+item.position+')')
    }
    if(location.map==current_map.name){
      device_filter_list.push(item)
    }
  })
  return device_filter_list
}
console.log(device,current_map)
var current_map_device=filter_current_func(device,'device')
console.log('current_map_device==>',current_map_device,device)
device_list_table(current_map_device)
dev_status_num('all','全部',current_map_device)
tree_render('id_tree',user_tree,current_map_device)
var current_map_building=filter_current_func(building,'building')
var current_map_scanner=filter_current_func(scanner,'scanner')

// 监听设备搜索操作
form.on('submit(dev-search-btn)', function (data) {
  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(current_map_device,search_key,'user_name','device_id')
    // 表格重载
    device_list_table(search_result)
  }else{
    device_list_table(current_map_device)
  }
  return false;
});


// ----侧边栏模块end---- //



// 设备数据刷新函数
var get_new_device=function(ajax_url='get_new_device'){

  $.ajax({
        type: 'GET',
        url:"/dynamic/?what="+ajax_url,
        async:true,
        dataType: 'json',
        success: function(res) {
          //console.log('refresh_device')
          var dev_data=res.data
          for(var i=0;i<dev_data.length;i++){
            if(dev_data[i]['device_id'] in checkDiv){
              dev_data[i]["LAY_CHECKED"]=true
            }
          }
          device=res.data
          current_map_device=filter_current_func(dev_data,'device')
          // device_list_table(current_map_device)
          device_statistic_func(current_map_device)
          //console.log(s_data)

          var total_num=current_map_device.length
          var out_room_num=total_num-in_room_num
          $('#in_room_num').text('室内：'+in_room_num.toString())
          $('#total_num').text('总数：'+total_num.toString())
          $('#out_room_num').text('室外：'+out_room_num.toString())
          // $('#danger_room_num').text('室内：'+in_room_num.toString())

        },
      });

}


// 刷新数据
interval_func=setInterval(get_new_device,param_refresh_time_control)

// ----显示地图覆盖物内容start---- //

var map_obj;
var group
var show_map_content=function(overlay){
  for(var k in overlay){
    for(var i=0;i<overlay[k].length;i++){
      var overlayonmap=overlay[k][i]
      var position=overlayonmap.position
      if(position!='' && position!='0'){
        position=eval('('+position+')')
        if(position.map==current_map.name && position.location!=''){
          // console.log(overlayonmap)
          add_static_marker(overlayonmap,k,'map_box')
        }
      }
    }
  }

  $('#map_box').on('click', function(event) {
    var target_obj=event.target
    // console.log(event)
    // console.log(target_obj.name)
    var x = event.offsetX
    var y = event.offsetY
    // console.log(x,y)

    if( target_obj.name!=null){
      var marker_info=target_obj.name.split(',')
      var unique=marker_info[0]
      var kind=marker_info[1]
      if(kind=='device'){
        tracker_marker_inforwindow(unique,kind)
      }else{
        static_marker_inforwindow(unique,kind)
      }
    }
  })

}


// ----打开fmap地图start---- //
if(map_data.length!=0){
  open_pngmap('map_box',current_map,user_self_name)
  var overlay_obj={}
  if(current_map_building.length!==0){
    overlay_obj.building=current_map_building
  }
  if(current_map_scanner.length!=0){
    overlay_obj.scanner=current_map_scanner
  }
  console.log(current_map_scanner)
  show_map_content(overlay_obj)
  // 加载本地图建筑
  fill_option(current_map_building,'building_select','name')
  // 加载本地图基站
  fill_option(current_map_scanner,'scanner_select','device_id')
  //加载地区切换
  for (var i = 0;i<map_data.length ; i++) {
    console.log(map_data[i].name)
    var option='<option>'+map_data[i].name+'</option>'
    if(map_data[i].name==current_map.name){
      option='<option selected>'+map_data[i].name+'</option>'
    }
    $('#select_map').append(option)
  }
  form.render()
  // $('#map_list').val(current_map.name)
}else{
  layer.msg('无地图')
}
// ----打开fmap地图end---- //

// 监听地图切换
form.on('select(map)',function(obj){
  // console.log(obj.value)
  current_map=get_detail_from_id(map_data,obj.value,'name')
  var page='monitor';
  layui.data('current_map',{key:'current_map',value:JSON.stringify(current_map)})
  window.history.pushState(null, null, "/index/#"+current_map.kind+'_'+page)
  turn_to_page(page)
})


// 查找建筑、基站
var query_func=function(kind,value){
  var target_obj=static_marker_obj[value]
  if(target_obj==null){
    layer.msg(value+'没有设置位置')
    return
  }
  if(target_obj.show!=false){
    static_marker_inforwindow(value,kind)
    // console.log(target_obj)
  }else{
    layer.msg('显示功能关闭')
  }
}

// 监听设备列表点击 
var checkDiv=new Array();
table.on('row(dev_list_show)', function(obj){
  click_dev_id(obj)
  layer.closeAll()
});

// -----点击设备链表，勾选功能--------//
var click_dev_id=function(obj){//选中行同步选中复选按钮
  var tr = obj.tr;
  var div = tr.find("div.layui-unselect");
  //checkDiv为定义的属性用来缓存当前点击的行是否选中状态，未选择的选中，选中的取消选中，并进行相应的地图打点处理
  // console.log(obj.data.device_id)
  if(!checkDiv[obj.data.device_id]) {
    checkDiv[obj.data.device_id] = obj;
    div.addClass("layui-form-checked");
    add_tracker_marker(obj.data,'map_box')
    chosed_dev=obj.data
    
  } else {
    div.removeClass("layui-form-checked");
    delete checkDiv[obj.data.device_id];
    remove_tracker_marker(obj.data.device_id)

    chosed_dev=''
  }
}


form.on('switch(overlay_show_sw)',function(obj){
  // console.log(obj.elem.checked,obj.elem.name)
  hide_static_marker(obj.elem.name,obj.elem.checked)
})
// ----删除/隐藏marker函数 end----- //


// 获取覆盖物详情
var get_overlay_detail=function(kind,overlay_target){
	
	var overlay=eval(kind)
  // console.log(overlay,kind,overlay_target)
	var detail;
	for (var i = overlay.length - 1; i >= 0; i--) {
		var name;
		if(kind=='building'){
			name=overlay[i]['name']
		}else{
			name=overlay[i]['device_id']
		}
	    if(overlay_target==name){
	    	detail=overlay[i]
	    }
	}
	// console.log(detail)
	return detail
}


// 报警参数功能js部分开始
// 监听报警参数设置
var set_param=function(device_id,status){
    // console.log(chosed_dev)
    document.getElementById("set_param_form").reset();
    var param_set={}
    // console.log(chosed_dev,param_set)
    if(chosed_dev['param_set']!='0' && chosed_dev['param_set']!=''){
      param_set=eval(chosed_dev['param_set'])
      if(param_set.quake_alarm=='off'){
        param_set.quake_alarm=false
      }
    }
    param_set.device_id=chosed_dev.device_id

    // 把设备之前的参数设置赋值给form
    form.val("set_param_form",param_set)
    layer.open({
        type: 1
        ,title:'报警参数设置: '
        // ,area:['700px','600px']
        ,offset:'100px'  
        ,id: 'set_param' //防止重复弹出
        ,content:$('#set_param_form')
        ,shade: 0 //不显示遮罩
      });
};
// 报警参数设置上传后台
form.on('submit(set_param_submit)', function (data) {
    var base_info = data.field;
    if(base_info.quake_alarm==null){
      base_info.quake_alarm='off'
    }
    // console.log(base_info)
    base_info_ajax(base_info,'dynamic','alarm_set',device_list_table)
    return false;
});

// 标签位置实时变化渲染
// lng,lat,坐标
// 室内外判断，室内，图标隐藏，室内标签数量增加，室外正常移动
// 室内室外危险区域标签数分类统计
var in_room_num=0;
device_statistic_func=function(data){
  in_room_num=0
  // console.log(fn_map)
  for(var i=0;i<data.length;i++){
    var dynamic=data[i].dynamic
    
    if (dynamic.location.building=='') {
      move_tracker_marker(data[i].device_id,dynamic.lng,dynamic.lat)
    }else{
      hide_tracker_marker(data[i].device_id,false)
      // tracker_marker_obj[data[i].device_id].setPosition(dynamic.lng,dynamic.lat)
      var build_name=dynamic.location.building
      // console.log(build_name,building_obj[build_name])
      // building_obj[build_name].asset.push(data[i].device_id)
      in_room_num=in_room_num+1
      
    }
    
  }
  // 建筑
  for(var i=0;i<building.length;i++){
    var title=building[i].name+'('+building[i].asset.length.toString()+')'
    $('#'+building[i].name).attr('name',title)
  }
}


function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

// // 模拟数据函数
// var simulate_times=0
// var simulate_data_func=function(d){

//   in_room_num=0
//   for(var i=0;i<building.length;i++){
//     building[i].asset=[]
//   }
//   for(var i=0;i<d.length;i++){
//     var ran_num=getRndInteger(-10,10)
//     if(d[i].dynamic.lng=='0'){
//       d[i].dynamic.lng=getRndInteger(12516026.32589589,12516326.32589589)
//       d[i].dynamic.lat=getRndInteger(4538147.677642516,4538347.677642516)
//     }
//     // console.log(d[i].dynamic.lng,ran_num)
//     d[i].dynamic.lng=d[i].dynamic.lng+ran_num
//     d[i].dynamic.lat=d[i].dynamic.lat+ran_num
//     // d[i].dynamic.lng=getRndInteger(12516026.32589589,12516326.32589589)
//     // d[i].dynamic.lat=getRndInteger(4538147.677642516,4538347.677642516)
//     var random_build=getRndInteger(0,building.length+20)
//     // console.log(building,random_build)
//     if(random_build<building.length){
//       d[i].dynamic.location=building[random_build].name
//     }else{
//       d[i].dynamic.location='0'
//     }
    
//   }
//   simulate_times=simulate_times+1
//   return d
// }

// repeat_func()
// interval_func=setInterval(repeat_func,5000)

</script>